package socket.test;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.Scanner;

import aos.entity.Message;
import aos.entity.MessageType;

public class TcpClient implements Runnable {
	private Socket socket;

	public TcpClient(String host, int port) throws IOException {
		System.out.println(host + " " + port);
		socket = new Socket(host, port);
		System.out.println(socket.getInetAddress().getHostAddress() + " "
				+ socket.getPort());
	}

	@Override
	public void run() {
		try {
			ObjectOutputStream os = new ObjectOutputStream(
					socket.getOutputStream());
			ObjectInputStream is = new ObjectInputStream(
					socket.getInputStream());

			Scanner cin = new Scanner(System.in);
			String line = null;
			while ((line = cin.nextLine()) != null) {
				if (line.equals("bye")) {
					break;
				}

				Message msg = new Message(0, 0, 1, MessageType.ACK);
				os.writeObject(msg);
				try {
					System.out.println(((Message) is.readObject()).toString());
				} catch (ClassNotFoundException e) {
					e.printStackTrace();
				}
			}
		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}

	public static void main(String[] args) throws Exception {
		// TcpClient client = new TcpClient("cloudhadoop.utdallas.edu", 9988);
		TcpClient client = new TcpClient("localhost", 9988);
		new Thread(client).start();
	}

}
